package com.djhu.es.core.request;
/**
 * Created by zw on 2017/12/28.
 */

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.SimpleQueryStringBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * <p>
 * ---------------------------------
 */
public class FulltextSearchRequest extends AbstractRequest implements SearchRequest {

    private List<String> fields;
    private Object key;
    private boolean searchAll = true;
    private String analyzer;

    public FulltextSearchRequest(){

    }

    public FulltextSearchRequest(List<String> fields, String key, boolean searchAll, String analyzer) {
        this.fields = fields;
        this.key = key;
        this.searchAll = searchAll;
        this.analyzer = analyzer;
    }

    public FulltextSearchRequest(String index, String type, int timeout, List<String> fields, Object key) {
        super(index, type, timeout);
        this.fields = fields;
        this.key = key;
    }

    @Override
    public QueryBuilder queryBuilder() {


        SimpleQueryStringBuilder simpleQueryStringBuilder =  QueryBuilders.simpleQueryStringQuery(String.valueOf(key));
        if (!StringUtils.isEmpty(this.analyzer)){
            simpleQueryStringBuilder = simpleQueryStringBuilder.analyzer(analyzer);
        }
        if (fields != null && searchAll == false){
            for (String field:fields) {
                simpleQueryStringBuilder = simpleQueryStringBuilder.field(field);
            }
        }else {
            //simpleQueryStringBuilder = simpleQueryStringBuilder.useAllFields(true);
            //simpleQueryStringBuilder.field()
//            simpleQueryStringBuilder.field("_all");
        }
        return simpleQueryStringBuilder;
    }

    public Object getKey() {
        return key;
    }

    public void setKey(Object key) {
        this.key = key;
    }

    public List<String> getFields() {
        return fields;
    }

    public void setFields(List<String> fields) {
        this.fields = fields;
    }

    public void addFields(String field) {
        if (this.fields == null){
            this.fields = new ArrayList<>();
            this.fields.add(field);
        }else {
            this.fields.add(field);
        }
    }

    public boolean isSearchAll() {
        return searchAll;
    }

    public void setSearchAll(boolean searchAll) {
        this.searchAll = searchAll;
    }
}